from sqlalchemy.exc import SQLAlchemyError
from flask_jwt_extended import create_access_token, create_refresh_token, decode_token
from datetime import datetime
import sys
sys.path.append("/")
from app.models.user import User, Role, TokenBlocklist, db, Department
from app.schemas.user import user_schema, user_update_schema, admin_user_update_schema, manager_change_user_role_schema, manager_change_user_department_schema



class UserService:
    @staticmethod
    def create_user(user_data):
        # 验证并加载数据


        user = user_schema.load(user_data)

        user.set_password(user_data['password'])

        # 分配默认角色
        default_role = Role.query.filter_by(name='normal_user').first()
        if default_role:
            user.roles.append(default_role)



        try:

            db.session.add(user)

            db.session.commit()

            return user_schema.dump(user), None


        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)


    @staticmethod
    def get_user_by_id(user_id):
        return User.query.get(user_id)

    @staticmethod
    def get_all_users():
        return User.query.all()

    @staticmethod
    def update_user(user_id, update_data):
        user = User.query.get(user_id)
        if not user:
            return None, "User not found"

        user_update_schema.session = db.session
        # 验证更新数据
        errors = user_update_schema.validate(update_data)
        if errors:
            return None, errors

        # 更新字段
        for key, value in update_data.items():
            if hasattr(user, key):
                setattr(user, key, value)

        try:

            db.session.commit()
            return user_schema.dump(user), None
        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)

    @staticmethod
    def delete_user(user_id):
        user = User.query.get(user_id)
        if not user:
            return False, "User not found"

        try:
            db.session.delete(user)
            db.session.commit()
            return True, None
        except SQLAlchemyError as e:
            db.session.rollback()
            return False, str(e)

    @staticmethod
    def revoke_token(jti):
        try:
            revoked_token = TokenBlocklist(jti=jti, created_at=datetime.utcnow())
            db.session.add(revoked_token)
            db.session.commit()
            return True
        except SQLAlchemyError:
            db.session.rollback()
            return False


    @staticmethod
    def admin_update_user(user_id, update_data):
        user = User.query.get(user_id)
        if not user:
            return None, "User not found"

        admin_user_update_schema.session = db.session
        # 验证更新数据
        errors = admin_user_update_schema.validate(update_data)
        if errors:
            return None, errors

        # 更新字段
        for key, value in update_data.items():
            if hasattr(user, key):
                setattr(user, key, value)

        try:

            db.session.commit()
            return user_schema.dump(user), None
        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)







    @staticmethod
    def check_manager_changer_user(manager_id):
        user = User.query.filter_by(id=manager_id).first()

        manager = Role.query.filter_by(name='general_manager').first()


        if manager in user.roles :
            return True
        else:
            return False



    @staticmethod
    def manager_change_user_role(user_id, update_data):
        user = User.query.get(user_id)
        if not user:
            return None, "User not found"

        manager_change_user_role_schema.session = db.session
        # 验证更新数据
        errors = manager_change_user_role_schema.validate(update_data)
        if errors:
            return None, errors

        user.roles.clear()
        for role in update_data.get('roles'):
            new_role = Role.query.filter_by(name=role).first()
            if new_role:
                user.roles.append(new_role)

        try:

            db.session.commit()
            return user_schema.dump(user), None
        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)

    @staticmethod
    def manager_change_user_department(user_id, update_data):
        user = User.query.get(user_id)
        if not user:
            return None, "User not found"

        manager_change_user_department_schema.session = db.session
        # 验证更新数据
        errors = manager_change_user_department_schema.validate(update_data)
        if errors:
            return None, errors



        new_department = Department.query.filter_by(name=update_data.get('department')).first()
        if new_department:
            user.department = new_department

        try:

            db.session.commit()
            return user_schema.dump(user), None
        except SQLAlchemyError as e:
            db.session.rollback()
            return None, str(e)

